<?php
/*
Plugin Name: Douban and Google Connect
Author:  lzyy
Author URI: http://blog.pianzhizhe.com/
Plugin URI: http://blog.pianzhizhe.com/archives/93
Description: 能够使用豆瓣和Google账号登陆你的WordPress博客(豆瓣登录部分参考了<a href="http://fairyfish.net/">Denis</a>的豆瓣登录插件)。
Version: 1.0
*/
if(!session_id())
{
	session_start();
}
$douban_consumer_key = '0d2c90cd302dee312785b2679089ca93';
$douban_consumer_secret = '059bf670f623445b';

$dc_loaded = false;

add_action('init', 'dc_gg_init');
add_filter("get_avatar", "dc_get_avatar",10,4);
add_action('comment_form', 'douban_connect_btn');

function dc_gg_init(){
	if(!is_user_logged_in()) {
        if(isset($_GET['oauth_token'])){
			if(strpos($_SERVER['HTTP_REFERER'],"douban.com")!==false){
				dc_confirm();
			} 
        } 
        if(isset($_GET['openid_op_endpoint']) AND strpos($_GET['openid_op_endpoint'],'google.com')!==false){
			gg_confirm();
        } 
    } 
}

function douban_connect_btn(){
    global $dc_loaded;

    if($dc_loaded || is_user_logged_in()) {
        return;
    }
	
	$dc_url = WP_PLUGIN_URL.'/douban-google-login/douban-start.php';
	$dc_btn_image = WP_PLUGIN_URL."/douban-google-login/douban_button.gif";

	$gg_url = WP_PLUGIN_URL.'/douban-google-login/google-start.php';
	$gg_btn_image = WP_PLUGIN_URL."/douban-google-login/google_button.gif";

	echo <<<EOT
	<style>
	#connent_login{padding:0 0 10px 0;}
	#connent_login a{text-decoration:none}
	#connent_login a:hover{text-decoration:none;border-bottom:none}
	</style>
EOT;
	echo '<p id="connent_login"><a href="'.$dc_url.'"><img src="'.$dc_btn_image.'" /></a> &nbsp;<a href="'.$gg_url.'"><img src="'.$gg_btn_image.'" /></a></p>';

    $dc_loaded = true;
}

function gg_confirm()
{
	if(!class_exists('GoogleOpenID'))
	{
		require 'google_openid.php';
	}
	$googleLogin = GoogleOpenID::getResponse();
	if($googleLogin->success()){
		$user_id = $googleLogin->identity();
		$email = $googleLogin->email();
		gg_login($email);
	} 
	else
	{
		echo 'auth failed';
	}
}

function dc_confirm(){
    global $douban_consumer_key, $douban_consumer_secret;
	
	if(!class_exists('DoubanOAuth')){
		include dirname(__FILE__).'/doubanOAuth.php';
	}
	$to = new DoubanOAuth($douban_consumer_key, $douban_consumer_secret, $_GET['oauth_token'],get_option('douban_oauth_token_secret'));
	
	$tok = $to->getAccessToken();

	$to = new DoubanOAuth($douban_consumer_key, $douban_consumer_secret, $tok['oauth_token'], $tok['oauth_token_secret']);
	
	$douban_info = $to->OAuthRequest('http://api.douban.com/people/%40me', array(), 'GET');
	if($douban_info == "no auth"){
		echo 'auth failed:(';
		return;
	}
	
	$douban_info = simplexml_load_string($douban_info);
	
	$douban_info_ns = $douban_info->children('http://www.douban.com/xmlns/');	

	$douban_user_id = str_replace("http://api.douban.com/people/","",$douban_info->id);
	$douban_user_url = "http://www.douban.com/people/".$douban_user_id;
		
	dc_login($douban_user_id.'|'.$douban_info->title.'|'.(string)$douban_info->link[3]['href'].'|'.$tok['oauth_token'] .'|'.$tok['oauth_token_secret']); 
}

function dc_login($douban_userinfo) {
	$userinfo = explode('|',$douban_userinfo);
	$userdata = array(
		'user_pass' => wp_generate_password(),
		'user_login' => 'douban_'.$userinfo[0],
		'display_name' => $userinfo[1],
		'user_url' => $userinfo[2],
		'user_email' => $userinfo[0].'@douban.com'
	);

	if(!function_exists('wp_insert_user')){
		include_once( ABSPATH . WPINC . '/registration.php' );
	} 
  
	$wpuid = get_user_by_login($userinfo[0]);
	
	if(!$wpuid){
		if($userinfo[0]){
			$wpuid = wp_insert_user($userdata);
		
			if($wpuid){
				update_usermeta($wpuid, 'dcid', $userinfo[0]);
				$dc_array = array (
					"oauth_access_token" => $userinfo[3],
					"oauth_access_token_secret" => $userinfo[4],
				);
				update_usermeta($wpuid, 'dcdata', $dc_array);
			}
		}
	} else {
		update_usermeta($wpuid, 'dcid', $userinfo[0]);
		$dc_array = array (
			"oauth_access_token" => $userinfo[3],
			"oauth_access_token_secret" => $userinfo[4],
		);
		update_usermeta($wpuid, 'dcdata', $dc_array);
	}
  
	if($wpuid) {
		wp_set_auth_cookie($wpuid, true, false);
		wp_set_current_user($wpuid);
	}

	if(!empty($_SESSION['connect_prev_url']))
	{
		$prev_url = $_SESSION['connect_prev_url'];
		header("Location: $prev_url");
		exit;
	}
	
}

function gg_login($email)
{
	$username = current(explode('@',$email));
	$userdata = array(
		'user_pass' => wp_generate_password(),
		'user_login' => 'google_'.$username,
		'display_name' => $username,
		'user_email' => $email
	);

	if(!function_exists('wp_insert_user')){
		include_once( ABSPATH . WPINC . '/registration.php' );
	} 
  
	$wpuid = get_gg_user_by_login($username);
	
	if(!$wpuid AND $email){
		$wpuid = wp_insert_user($userdata);
	}
  
	if($wpuid) {
		wp_set_auth_cookie($wpuid, true, false);
		wp_set_current_user($wpuid);
	}
	if(!empty($_SESSION['connect_prev_url']))
	{
		$prev_url = $_SESSION['connect_prev_url'];
		header("Location: $prev_url");
		exit;
	}
	
}

function get_user_by_login($user_login) {
  global $wpdb;
  $sql = "SELECT ID FROM $wpdb->users WHERE user_login = '%s'";
  return $wpdb->get_var($wpdb->prepare($sql, 'douban_'.$user_login));
}

function get_gg_user_by_login($user_login)
{
  global $wpdb;
  $sql = "SELECT ID FROM $wpdb->users WHERE user_login = '%s'";
  return $wpdb->get_var($wpdb->prepare($sql, 'google_'.$user_login));
}

function dc_get_avatar($avatar, $id_or_email='',$size='32') {
	global $comment;
	if(is_object($comment)) {
		$id_or_email = $comment->user_id;
	}
	if (is_object($id_or_email)){
		$id_or_email = $id_or_email->user_id;
	}
	if($dcid = get_usermeta($id_or_email, 'dcid')){
		$out = 'http://t.douban.com/icon/u'.$dcid.'-1.jpg';
		$avatar = "<img alt='' src='{$out}' class='avatar avatar-{$size}' height='{$size}' width='{$size}' />";
		return $avatar;
	}else {
		return $avatar;
	}
}

